Count and Say

The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence.

题目大意:数字计数并说出来,例如1,读作1个1(11);11读作2个1(21);21->1211->111221->312211

/**
 * Created by gzdaijie on 16/5/9
 * 递归,n为1时是出口
 * 在字符串最后添加字符‘#’,是为了统一解决字符计数的问题
 */
public class Solution {
    public String countAndSay(int n) {
        if (n == 1) return "1";

        String pre = countAndSay(n - 1) + '#';
        int len = pre.length();
        int count = 1;
        char ch = pre.charAt(0);
        String result = "";
        for (int i = 1; i < len; i++) {
            if (ch == pre.charAt(i)) {
                ++count;
            } else {
                result += (char)(count + '0');
                result += ch;
                count = 1;
                ch = pre.charAt(i);
            }
        }
        return result;
    }
}
/**
 * Created by gzdaijie on 16/5/9
 * 尾递归改循环,复杂度不变
 * 字符串拼接非常耗时,字符串拼接改为数组操作(运行时间 34ms -> 1ms)
 */
public class Solution {
    public String countAndSay(int n) {
        String result = "1";
        for (int i = 1; i < n; i++) {
            result = generateNext(result);
        }
        return result;
    }
    private String generateNext(String pre) {
        pre = pre + '#';
        int len = pre.length();
        int count = 1;
        char ch = pre.charAt(0);
        int k = 0;
        char[] result = new char[len * 2];
        for (int i = 1; i < len; i++) {
            if (ch == pre.charAt(i)) {
                ++count;
            } else {
                result[k++] = (char)(count + '0');
                result[k++] = ch;
                count = 1;
                ch = pre.charAt(i);
            }
        }
        return String.valueOf(result, 0 ,k);
    }
}
gzdaijie            updated 2016-05-09 17:01:52

results matching ""

    No results matching ""